package com.bookocean.controller;

import com.bookocean.application.common.Result;
import com.bookocean.application.service.NovelApplicationService;
import com.bookocean.domain.service.NovelCompleteVoteService;
import com.bookocean.controller.dto.NovelDto;
import com.bookocean.controller.dto.NovelChapterDto;
import com.bookocean.controller.dto.NovelParticipantDto;
import com.bookocean.controller.dto.NovelCompleteVoteDto;
import com.bookocean.domain.utils.UserContextHolder;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 小说控制器
 * 
 * @author BookOcean
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/novel")
@RequiredArgsConstructor
public class NovelController {

    private final NovelApplicationService novelApplicationService;
    private final NovelCompleteVoteService novelCompleteVoteService;

    /**
     * 创建小说
     */
    @PostMapping("/create")
    public Result<NovelDto> createNovel(@Valid @RequestBody NovelDto novelDto) {
        NovelDto createdNovel = novelApplicationService.createNovel(novelDto);
        return Result.success(createdNovel);
    }

    /**
     * 根据ID查询小说基本信息
     */
    @GetMapping("/{novelId}")
    public Result<NovelDto> getNovelById(@PathVariable Long novelId) {
        NovelDto novel = novelApplicationService.getNovelById(novelId);
        return Result.success(novel);
    }

    /**
     * 根据ID查询小说详细信息（包含统计数据和用户交互状态）
     */
    @GetMapping("/{novelId}/enhanced")
    public Result<NovelDto> getEnhancedNovelById(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelDto novel = novelApplicationService.getEnhancedNovelById(novelId, currentUserId);
        return Result.success(novel);
    }

    /**
     * 更新小说信息
     */
    @PutMapping("/update")
    public Result<NovelDto> updateNovel(@Valid @RequestBody NovelDto novelDto) {
        NovelDto updatedNovel = novelApplicationService.updateNovel(novelDto);
        return Result.success(updatedNovel);
    }

    /**
     * 完结小说
     */
    @PostMapping("/{novelId}/complete")
    public Result<NovelDto> completeNovel(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelDto completedNovel = novelApplicationService.completeNovel(novelId, currentUserId);
        return Result.success(completedNovel);
    }

    /**
     * 查询我参与的小说列表
     */
    @GetMapping("/my-participated")
    public Result<List<NovelDto>> getMyParticipatedNovels(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Long currentUserId = UserContextHolder.getUserId();
        List<NovelDto> novels = novelApplicationService.getUserParticipatedNovels(currentUserId, page, pageSize);
        return Result.success(novels);
    }

    /**
     * 查询正在招募的小说列表
     */
    @GetMapping("/recruiting")
    public Result<List<NovelDto>> getRecruitingNovels(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        List<NovelDto> novels = novelApplicationService.getRecruitingNovels(page, pageSize);
        return Result.success(novels);
    }

    /**
     * 查询已完结小说列表（按热度排序）
     */
    @GetMapping("/completed")
    public Result<List<NovelDto>> getCompletedNovels(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        List<NovelDto> novels = novelApplicationService.getCompletedNovels(page, pageSize);
        return Result.success(novels);
    }

    /**
     * 加入小说创作
     */
    @PostMapping("/{novelId}/join")
    public Result<NovelParticipantDto> joinNovel(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelParticipantDto participant = novelApplicationService.joinNovel(novelId, currentUserId);
        return Result.success(participant);
    }

    /**
     * 查询小说参与者列表
     */
    @GetMapping("/{novelId}/participants")
    public Result<List<NovelParticipantDto>> getNovelParticipants(@PathVariable Long novelId) {
        List<NovelParticipantDto> participants = novelApplicationService.getNovelParticipants(novelId);
        return Result.success(participants);
    }

    /**
     * 写新章节
     */
    @PostMapping("/chapter/write")
    public Result<NovelChapterDto> writeChapter(@Valid @RequestBody NovelChapterDto chapterDto) {
        Long currentUserId = UserContextHolder.getUserId();
        chapterDto.setAuthorId(currentUserId);
        NovelChapterDto chapter = novelApplicationService.writeChapter(chapterDto);
        return Result.success(chapter);
    }

    /**
     * 查询小说章节列表
     */
    @GetMapping("/{novelId}/chapters")
    public Result<List<NovelChapterDto>> getNovelChapters(@PathVariable Long novelId) {
        List<NovelChapterDto> chapters = novelApplicationService.getNovelChapters(novelId);
        return Result.success(chapters);
    }

    /**
     * 查询章节详细信息（包含统计数据和用户交互状态）
     */
    @GetMapping("/chapter/{chapterId}")
    public Result<NovelChapterDto> getChapterById(@PathVariable Long chapterId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelChapterDto chapter = novelApplicationService.getEnhancedChapterById(chapterId, currentUserId);
        return Result.success(chapter);
    }

    /**
     * 检查是否可以写下一章
     */
    @GetMapping("/{novelId}/can-write")
    public Result<Boolean> canWriteNextChapter(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        boolean canWrite = novelApplicationService.canWriteNextChapter(novelId, currentUserId);
        return Result.success(canWrite);
    }

    // ============================= 完结投票相关接口 =============================

    /**
     * 发起完结投票
     */
    @PostMapping("/{novelId}/complete/vote")
    public Result<NovelCompleteVoteDto> initiateCompleteVote(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelCompleteVoteDto vote = novelCompleteVoteService.initiateCompleteVote(novelId, currentUserId);
        return Result.success(vote);
    }

    /**
     * 投票同意完结
     */
    @PostMapping("/{novelId}/complete/vote/agree")
    public Result<NovelCompleteVoteDto> voteForComplete(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelCompleteVoteDto vote = novelCompleteVoteService.voteForComplete(novelId, currentUserId);
        return Result.success(vote);
    }

    /**
     * 投票反对完结
     */
    @PostMapping("/{novelId}/complete/vote/oppose")
    public Result<NovelCompleteVoteDto> voteAgainstComplete(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelCompleteVoteDto vote = novelCompleteVoteService.voteAgainstComplete(novelId, currentUserId);
        return Result.success(vote);
    }

    /**
     * 取消完结投票
     */
    @PostMapping("/{novelId}/complete/vote/cancel")
    public Result<Boolean> cancelCompleteVote(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        boolean result = novelCompleteVoteService.cancelCompleteVote(novelId, currentUserId);
        return Result.success(result);
    }

    /**
     * 获取完结投票状态
     */
    @GetMapping("/{novelId}/complete/vote/status")
    public Result<NovelCompleteVoteDto> getCompleteVoteStatus(@PathVariable Long novelId) {
        Long currentUserId = UserContextHolder.getUserId();
        NovelCompleteVoteDto vote = novelCompleteVoteService.getCompleteVoteStatus(novelId, currentUserId);
        return Result.success(vote);
    }
}
